<template>
  <div v-if="show" class="modal-overlay" @click="$emit('update:show', false)">
    <div class="modal-content login-modal" @click.stop>
      <!-- 高级背景效果 -->
      <div class="background-effects">
        <div class="gradient-orbs">
          <div class="orb orb-1"></div>
          <div class="orb orb-2"></div>
          <div class="orb orb-3"></div>
        </div>
        <div class="grid-pattern"></div>
      </div>

      <div class="modal-header">
        <div class="logo-container">
          <div class="logo-wrapper">
            <!-- 艺术感图标 -->
            <div class="logo-icon artistic-icon">
              <div class="icon-shape">
                <div class="fitness-symbol">
                  <div class="weight-circle"></div>
                  <div class="energy-wave"></div>
                  <div class="motion-line"></div>
                </div>
              </div>
            </div>
            <div class="logo-text">
              <h1>FitPro</h1>
              <span>用户登录</span>
            </div>
          </div>
        </div>
        <div class="welcome-text">
          <h2>欢迎回来</h2>
          <p>请登录您的健身账户</p>
        </div>
        <button class="close-btn" @click="$emit('update:show', false)">&times;</button>
      </div>

      <form @submit.prevent="handleSubmit" class="login-form">
        <div class="form-group">
          <div class="input-container">
            <div class="input-icon">
              <i class="fas fa-phone"></i>
            </div>
            <input
                id="mobile"
                v-model="loginForm.mobile"
                type="text"
                class="form-input"
                placeholder="请输入手机号"
                required
            />
            <div class="input-border"></div>
            <div class="input-highlight"></div>
          </div>
        </div>

        <div class="form-group">
          <div class="input-container">
            <div class="input-icon">
              <i class="fas fa-lock"></i>
            </div>
            <input
                id="password"
                v-model="loginForm.password"
                type="password"
                class="form-input"
                placeholder="请输入密码"
                required
            />
            <div class="input-border"></div>
            <div class="input-highlight"></div>
          </div>
        </div>

        <div class="form-options">
          <label class="checkbox-container">
            <input type="checkbox" v-model="rememberMe" />
            <span class="checkmark"></span>
            <span class="checkbox-label">记住登录状态</span>
          </label>
          <a href="#" class="forgot-link">忘记密码？</a>
        </div>

        <div class="form-buttons">
          <button type="submit" class="login-button" :class="{ 'loading': isLoading }">
            <span class="button-text" v-if="!isLoading">
              <i class="fas fa-sign-in-alt"></i>
              立即登录
            </span>
            <span class="button-loading" v-else>
              <i class="fas fa-spinner fa-spin"></i>
              登录中...
            </span>
            <div class="button-shine"></div>
          </button>
          <button type="button" class="register-btn" @click="showRegister">
            <i class="fas fa-user-plus"></i>
            注册账户
          </button>
        </div>
      </form>

      <!-- 消息提示框部分 -->
      <div v-if="errorMessage || successMessage"
           class="message-box"
           :class="successMessage ? 'success-message' : 'error-message'">
        <div class="message-icon">
          <i :class="successMessage ? 'fas fa-check-circle' : 'fas fa-exclamation-triangle'"></i>
        </div>
        <span>{{ successMessage || errorMessage }}</span>
      </div>

      <!-- 底部信息 -->
      <div class="login-footer">
        <div class="security-info">
          <i class="fas fa-shield-check"></i>
          <span>💪 强健体魄，从登录开始</span>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { ref } from 'vue'
import { useRouter } from 'vue-router'
import axios from 'axios'
import { useUserStore } from '@/stores/auth'

export default {
  name: 'LoginModal',
  props: {
    show: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:show', 'showRegister'],
  setup(props, { emit }) {
    const router = useRouter()
    const userStore = useUserStore()

    const loginForm = ref({
      mobile: '',
      password: ''
    })
    const errorMessage = ref('')
    const successMessage = ref('')
    const rememberMe = ref(false)
    const isLoading = ref(false)

    const showRegister = () => {
      emit('update:show', false)
      emit('showRegister', true)
    }

    const handleSubmit = async () => {
      errorMessage.value = ''
      successMessage.value = ''
      isLoading.value = true

      // 输入验证
      if (!loginForm.value.mobile.trim()) {
        errorMessage.value = '请输入手机号'
        isLoading.value = false
        return
      }

      if (!loginForm.value.password.trim()) {
        errorMessage.value = '请输入密码'
        isLoading.value = false
        return
      }

      try {
        // 调用后端登录API
          const response = await axios.post('/api/users/login', {
            mobile: loginForm.value.mobile,
            password: loginForm.value.password
          })

          console.log('登录响应:', response.data) // 调试用

          // 修复：根据后端的 Result 结构判断成功
          if (response.data && response.data.code === 200) {
            try {
              let userData = response.data.data
              console.log('登录成功，用户数据:', userData)

              // 使用后端返回的真实token
              const tokenToUse = userData.token || '';
              if (tokenToUse) {
                localStorage.setItem('userToken', tokenToUse);
                console.log('LoginModal - 使用后端返回的token');
              } else {
                // 如果后端没有返回token，生成一个包含时间戳的临时token以确保每次都不同
                const tempToken = 'user-token-temp-' + Date.now();
                localStorage.setItem('userToken', tempToken);
                console.log('LoginModal - 后端未返回token，使用临时token');
              }
              
              // 尝试获取最新用户信息，但即使失败也不影响登录流程
              try {
                const userId = userData.userId || userData.id || userData.uId
                if (userId) {
                  console.log('LoginModal - 调用getUserInfo获取最新用户信息，用户ID:', userId)
                  const userInfoResponse = await axios.get(`/api/users/${userId}`)
                  
                  if (userInfoResponse.data && (userInfoResponse.data.code === 200 || userInfoResponse.data.success)) {
                    userData = userInfoResponse.data.data
                    console.log('LoginModal - 获取到的完整用户信息:', userData)
                  }
                }
              } catch (userInfoError) {
                console.warn('LoginModal - 获取用户详细信息失败，继续使用登录响应中的数据:', userInfoError)
                // 不抛出错误，继续使用登录时获取的数据
              }
              
              // 保存用户信息到localStorage
              localStorage.setItem('userInfo', JSON.stringify(userData))
              localStorage.setItem('userId', userData.userId || userData.id || userData.uId || 'unknown')
              
              // 更新Pinia状态管理中的用户信息
              console.log('调用userStore.setUserInfo前的状态:', { isLoggedIn: userStore.isLoggedIn, token: userStore.token })
              userStore.setUserInfo(userData)
              console.log('调用userStore.setUserInfo后的状态:', { isLoggedIn: userStore.isLoggedIn, token: userStore.token })

              // 显示成功消息
              successMessage.value = response.data.message || '登录成功！正在跳转...'

              // 延迟关闭模态框并重置表单
              setTimeout(() => {
                emit('update:show', false)
                loginForm.value.mobile = ''
                loginForm.value.password = ''

                // 跳转到用户仪表板
                router.replace('/user/dashboard')
              }, 1500)
            } catch (loginProcessError) {
              console.error('登录成功但处理后续流程时出错:', loginProcessError)
              // 即使处理后续流程出错，也设置成功状态，因为登录本身成功了
              successMessage.value = '登录成功！'
              
              // 保存基本的登录状态
              localStorage.setItem('userToken', 'user-token-success-' + Date.now())
              
              setTimeout(() => {
                emit('update:show', false)
                router.replace('/user/dashboard')
              }, 1500)
            }
          } else {
            // 如果code不是200，显示错误消息
            errorMessage.value = response.data.message || '登录失败'
          }
      } catch (error) {
        console.error('登录失败:', error)

        // 根据后端错误响应结构调整
        if (error.response && error.response.data) {
          // 后端返回的 Result 对象
          const result = error.response.data
          if (result.message) {
            errorMessage.value = result.message
          } else if (result.code !== 200) {
            errorMessage.value = result.message || '登录失败'
          } else {
            errorMessage.value = '登录失败，请检查手机号和密码'
          }
        } else if (error.code === 'ECONNREFUSED' || error.message?.includes('ECONNREFUSED')) {
          errorMessage.value = '后端服务暂不可用，请检查服务是否启动'
        } else if (error.request) {
          errorMessage.value = '无法连接到服务器，请检查网络连接'
        } else {
          errorMessage.value = '登录过程中发生错误，请稍后重试'
        }
      } finally {
        isLoading.value = false
      }
    }

    return {
      loginForm,
      errorMessage,
      successMessage, // 返回成功消息
      rememberMe,
      isLoading,
      showRegister,
      handleSubmit
    }
  }
}
</script>

<style scoped>
/* 消息框基础样式 */
.message-box {
  display: flex;
  align-items: center;
  gap: 0.75rem;
  border-radius: 8px;
  padding: 1rem;
  margin-bottom: 1.5rem;
  animation: slideIn 0.5s ease-in-out;
}

/* 错误消息样式 - 使用更具体的选择器 */
.message-box.error-message {
  background: rgba(220, 38, 38, 0.1);
  border: 1px solid rgba(220, 38, 38, 0.2);
}

/* 成功消息样式 - 使用更具体的选择器 */
.message-box.success-message {
  background: rgba(34, 197, 94, 0.1);
  border: 1px solid rgba(34, 197, 94, 0.2);
}

/* 图标样式 */
.message-box .message-icon {
  font-size: 0.9rem;
}

.message-box.error-message .message-icon {
  color: #dc2626;
}

.message-box.success-message .message-icon {
  color: #22c55e;
}

/* 文字样式 */
.message-box.error-message span {
  color: #ef4444;
  font-size: 0.85rem;
  font-weight: 500;
}

.message-box.success-message span {
  color: #22c55e;
  font-size: 0.85rem;
  font-weight: 500;
}

@keyframes slideIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 艺术感图标样式 */
.artistic-icon {
  width: 60px;
  height: 60px;
  position: relative;
  display: flex;
  align-items: center;
  justify-content: center;
}

.icon-shape {
  width: 100%;
  height: 100%;
  position: relative;
  transform-style: preserve-3d;
  animation: float-icon 3s ease-in-out infinite;
}

.fitness-symbol {
  width: 100%;
  height: 100%;
  position: relative;
}

/* 重量圆圈 */
.weight-circle {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 40px;
  height: 40px;
  border: 3px solid;
  border-color: #667eea;
  border-radius: 50%;
  background: conic-gradient(
      from 0deg,
      transparent 0deg 180deg,
      rgba(102, 126, 234, 0.3) 180deg 360deg
  );
  animation: rotate-circle 8s linear infinite;
}

.weight-circle::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 20px;
  height: 20px;
  background: radial-gradient(circle, #764ba2 0%, #667eea 100%);
  border-radius: 50%;
  box-shadow: 0 0 15px rgba(118, 75, 162, 0.5);
}

/* 能量波纹 */
.energy-wave {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 50px;
  height: 50px;
  border: 2px solid;
  border-color: rgba(102, 126, 234, 0.3);
  border-radius: 50%;
  animation: pulse-wave 2s ease-out infinite;
}

.energy-wave::before {
  content: '';
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
  border: 1px solid;
  border-color: rgba(118, 75, 162, 0.2);
  border-radius: 50%;
  animation: pulse-wave 2s ease-out infinite 0.5s;
}

/* 运动线条 */
.motion-line {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 60px;
  height: 60px;
}

.motion-line::before,
.motion-line::after {
  content: '';
  position: absolute;
  background: linear-gradient(90deg, transparent, #667eea, transparent);
  height: 2px;
  border-radius: 1px;
}

.motion-line::before {
  top: 10px;
  left: 0;
  width: 100%;
  transform: rotate(45deg);
  animation: shine-line 3s ease-in-out infinite;
}

.motion-line::after {
  bottom: 10px;
  left: 0;
  width: 100%;
  transform: rotate(-45deg);
  animation: shine-line 3s ease-in-out infinite 1.5s;
}

/* 动画定义 */
@keyframes float-icon {
  0%, 100% {
    transform: translateY(0px) rotate(0deg);
  }
  50% {
    transform: translateY(-5px) rotate(5deg);
  }
}

@keyframes rotate-circle {
  0% {
    transform: translate(-50%, -50%) rotate(0deg);
  }
  100% {
    transform: translate(-50%, -50%) rotate(360deg);
  }
}

@keyframes pulse-wave {
  0% {
    transform: translate(-50%, -50%) scale(0.8);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, -50%) scale(1.2);
    opacity: 0;
  }
}

@keyframes shine-line {
  0%, 100% {
    opacity: 0.3;
    background: linear-gradient(90deg, transparent, rgba(102, 126, 234, 0.5), transparent);
  }
  50% {
    opacity: 1;
    background: linear-gradient(90deg, transparent, #667eea, transparent);
  }
}

.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  backdrop-filter: blur(10px);
  animation: fadeIn 0.3s ease;
}

.modal-content {
  background: rgba(15, 23, 42, 0.8);
  backdrop-filter: blur(25px);
  border-radius: 20px;
  padding: 2.5rem 3rem;
  width: 90%;
  max-width: 480px;
  box-shadow:
      0 25px 50px rgba(0, 0, 0, 0.4),
      inset 0 1px 0 rgba(255, 255, 255, 0.1),
      0 0 0 1px rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  position: relative;
  overflow: hidden;
  animation: slideUp 0.3s ease;
}

.modal-content::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  height: 1px;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.4), transparent);
}

/* 背景效果 */
.background-effects {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  pointer-events: none;
}

.gradient-orbs {
  position: relative;
  width: 100%;
  height: 100%;
}

.orb {
  position: absolute;
  border-radius: 50%;
  filter: blur(60px);
  opacity: 0.15;
  animation: float 8s ease-in-out infinite;
}

.orb-1 {
  width: 200px;
  height: 200px;
  top: 10%;
  left: 10%;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  animation-delay: 0s;
}

.orb-2 {
  width: 180px;
  height: 180px;
  top: 60%;
  right: 15%;
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  animation-delay: 2s;
}

.orb-3 {
  width: 160px;
  height: 160px;
  bottom: 20%;
  left: 20%;
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
  animation-delay: 4s;
}

.grid-pattern {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-image:
      linear-gradient(rgba(255,255,255,0.03) 1px, transparent 1px),
      linear-gradient(90deg, rgba(255,255,255,0.03) 1px, transparent 1px);
  background-size: 40px 40px;
  opacity: 0.3;
}

@keyframes float {
  0%, 100% { transform: translateY(0px) scale(1); }
  50% { transform: translateY(-20px) scale(1.05); }
}

/* 顶部区域 */
.modal-header {
  text-align: center;
  margin-bottom: 2rem;
  position: relative;
}

.logo-container {
  margin-bottom: 1.5rem;
}

.logo-wrapper {
  display: inline-flex;
  align-items: center;
  gap: 1rem;
  background: rgba(255, 255, 255, 0.05);
  padding: 1rem 1.5rem;
  border-radius: 16px;
  border: 1px solid rgba(255, 255, 255, 0.1);
}

.logo-text h1 {
  font-size: 1.75rem;
  font-weight: 700;
  background: linear-gradient(135deg, #fff 0%, #cbd5e1 100%);
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  background-clip: text;
  margin: 0;
  line-height: 1.2;
}

.logo-text span {
  font-size: 0.75rem;
  color: #94a3b8;
  font-weight: 600;
  letter-spacing: 1px;
}

.welcome-text h2 {
  font-size: 1.5rem;
  font-weight: 600;
  color: #f8fafc;
  margin: 0 0 0.5rem 0;
}

.welcome-text p {
  color: #94a3b8;
  font-size: 0.95rem;
  margin: 0;
  font-weight: 400;
}

.close-btn {
  position: absolute;
  top: 1rem;
  right: 1rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #94a3b8;
  padding: 0.5rem;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 1.2rem;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border-color: rgba(255, 255, 255, 0.2);
}

/* 表单样式 */
.login-form {
  margin-bottom: 1.5rem;
}

.form-group {
  margin-bottom: 1.5rem;
}

.input-container {
  position: relative;
}

.input-icon {
  position: absolute;
  left: 1rem;
  top: 50%;
  transform: translateY(-50%);
  color: #64748b;
  font-size: 1rem;
  z-index: 2;
  transition: color 0.3s ease;
}

.form-input {
  width: 100%;
  padding: 1.125rem 1rem 1.125rem 3rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.08);
  border-radius: 12px;
  font-size: 1rem;
  color: #f8fafc;
  transition: all 0.3s ease;
  position: relative;
  z-index: 1;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
}

.form-input::placeholder {
  color: #64748b;
}

.form-input:focus {
  outline: none;
  background: rgba(255, 255, 255, 0.08);
  border-color: rgba(102, 126, 234, 0.6);
  box-shadow: 0 0 0 3px rgba(102, 126, 234, 0.15);
}

.form-input:focus + .input-border {
  opacity: 1;
  transform: scaleX(1);
}

.form-input:focus ~ .input-highlight {
  opacity: 1;
  transform: scaleX(1);
}

.input-border {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: linear-gradient(90deg, #667eea, #764ba2);
  opacity: 0;
  transform: scaleX(0);
  transition: all 0.3s ease;
  border-radius: 0 0 12px 12px;
  z-index: 2;
}

.input-highlight {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: linear-gradient(135deg, rgba(102, 126, 234, 0.1), rgba(118, 75, 162, 0.1));
  border-radius: 12px;
  opacity: 0;
  transform: scaleX(0);
  transition: all 0.3s ease;
  z-index: 0;
}

/* 表单选项 */
.form-options {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
  font-size: 0.9rem;
}

.checkbox-container {
  display: flex;
  align-items: center;
  cursor: pointer;
  color: #cbd5e1;
  transition: color 0.3s ease;
}

.checkbox-container:hover {
  color: #f8fafc;
}

.checkbox-container input {
  display: none;
}

.checkmark {
  width: 18px;
  height: 18px;
  border: 2px solid #475569;
  border-radius: 4px;
  margin-right: 0.75rem;
  position: relative;
  transition: all 0.3s ease;
  background: rgba(255, 255, 255, 0.05);
}

.checkbox-container input:checked + .checkmark {
  background: #667eea;
  border-color: #667eea;
}

.checkbox-container input:checked + .checkmark::after {
  content: '✓';
  position: absolute;
  color: white;
  font-size: 0.8rem;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.checkbox-label {
  font-weight: 500;
}

.forgot-link {
  color: #94a3b8;
  text-decoration: none;
  transition: color 0.3s ease;
  font-weight: 500;
}

.forgot-link:hover {
  color: #667eea;
}

/* 按钮样式 */
.form-buttons {
  display: flex;
  gap: 1rem;
  margin-top: 2rem;
}

.login-button {
  flex: 2;
  padding: 1.125rem;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border: none;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
  overflow: hidden;
  box-shadow: 0 8px 25px rgba(102, 126, 234, 0.3);
}

.login-button:hover:not(.loading) {
  transform: translateY(-2px);
  box-shadow: 0 12px 30px rgba(102, 126, 234, 0.4);
}

.login-button:active {
  transform: translateY(0);
}

.login-button.loading {
  cursor: not-allowed;
  opacity: 0.8;
}

.button-text, .button-loading {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
  position: relative;
  z-index: 2;
}

.button-shine {
  position: absolute;
  top: 0;
  left: -100%;
  width: 100%;
  height: 100%;
  background: linear-gradient(90deg, transparent, rgba(255,255,255,0.2), transparent);
  transition: left 0.5s ease;
}

.login-button:hover .button-shine {
  left: 100%;
}

.register-btn {
  flex: 1;
  padding: 1.125rem;
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: #94a3b8;
  border-radius: 12px;
  font-size: 1rem;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0.5rem;
}

.register-btn:hover {
  background: rgba(255, 255, 255, 0.1);
  color: #f8fafc;
  border-color: rgba(255, 255, 255, 0.2);
  transform: translateY(-2px);
}

@keyframes shake {
  0%, 100% { transform: translateX(0); }
  25% { transform: translateX(-5px); }
  75% { transform: translateX(5px); }
}

/* 底部信息 */
.login-footer {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 1.5rem;
  border-top: 1px solid rgba(255, 255, 255, 0.1);
}

.security-info {
  display: flex;
  align-items: center;
  gap: 0.5rem;
  color: #64748b;
  font-size: 0.8rem;
  font-weight: 500;
}

.security-info i {
  color: #10b981;
}

/* 动画 */
@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .modal-content {
    padding: 2rem 1.5rem;
    margin: 1rem;
  }

  .logo-wrapper {
    flex-direction: column;
    gap: 0.75rem;
    text-align: center;
  }

  .form-options {
    flex-direction: column;
    gap: 1rem;
    align-items: flex-start;
  }

  .forgot-link {
    align-self: flex-end;
  }

  .form-buttons {
    flex-direction: column;
  }
}

@media (max-width: 480px) {
  .modal-content {
    padding: 1.5rem 1.25rem;
  }

  .logo-text h1 {
    font-size: 1.5rem;
  }

  .welcome-text h2 {
    font-size: 1.25rem;
  }
}
</style>